import React, { useState, useEffect } from 'react'
import { UploadOutlined } from '@ant-design/icons'
import { Button, Upload, message } from 'antd'
import { getAccessToken } from '@/utils/utils'
import { useModel } from '@umijs/max'

const UploadFile = props => {
  const { value, onChange, maxCount } = props

  const [fileList, setFileList] = useState([])

  useEffect(() => {
    if (value && value.length) {
      setFileList(value.map(i => ({ ...i, status: 'done' })))
    }
  }, [])
  const { UPLOAD_URL_FILE } = useModel('Global')
  const formatProps = {
    headers: {
      token: getAccessToken()
    },
    action: UPLOAD_URL_FILE,
    ...props,
    fileList,
    onChange({ file, fileList }) {
      setFileList(fileList)

      const present = fileList.filter(i => i.status === 'done')

      if (file.status === 'done' || file.status === 'removed') {
        const res = present.map(i => ({ name: i.name, url: i.url || i.response.data.file_url }))
        onChange(res)
      } else if (file.status === 'uploading' && present.length === maxCount) {
        message.warning(`最多上传${maxCount}个文件`)
      }
    }
  }

  return (
    <Upload {...formatProps}>
      <Button type='primary' icon={<UploadOutlined />}>
        点击上传
      </Button>
    </Upload>
  )
}
export default UploadFile
